<?php

namespace App\Jobs;

use App\Models\Mysql\XnMerchant;
use App\Models\Mysql\XnMerchantBill;
use App\Models\Mysql\XnOrder;
use App\Models\Mysql\XnOrderBill;
use App\Models\Mysql\XnTime;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\PartyRequest\RequestOrder;
class order implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    private $data;
    public function __construct($data = [])
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $this->order_db($this->data);
    }

    //订单入库
    public function order_db($data){
        DB::connection(request()->get('db', 'supplier'))->beginTransaction();
        try {
            $balance = XnMerchant::where('merchant_number',$data['order']['merchant_number'])->first();
            if (($balance->balance-$balance->deduction_balance) < $data['order']['all_money']){
                throw new \Exception('余额不足');
            }
            $year_month = date('Y-m',time());
            $year_month_arr = explode('-',$year_month);
            $time_infos = XnTime:: where(['year'=>$year_month_arr[0],'month'=>$year_month_arr[1]]) -> select('id') -> first();
            if(!$time_infos){
                XnTime:: insert([
                    'year' =>$year_month_arr[0],
                    'month' => $year_month_arr[1],
                    'ctime' => time()
                ]);
            }
            XnMerchant::where('merchant_number', $data['order']['merchant_number'])->increment('deduction_balance', $data['order']['all_money']);
            XnOrder::insert($data['order']);//入库订单表
            XnMerchantBill::insert($data['merchant_bill']);//入商户账单表
            XnOrderBill::insert($data['order_bill']);//入供应商账单表
            DB::connection(request()->get('db', 'supplier'))->commit();
            $request = new RequestOrder();
            $request->yipai($data);
        } catch (\Throwable $e) {
            DB::connection(request()->get('db', 'supplier'))->rollBack();
            Log::channel('order_job')->error($e->getMessage());
        }
    }
}
